<?php

namespace app\admin\controller\cms;

use app\admin\model\cms\PlazaPostModel;
use app\common\controller\Backend;
use app\common\model\User;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 评论管理
 *
 * @icon fa fa-comment
 */
class Comment extends Backend
{

    /**
     * Comment模型对象
     */
    protected $model = null;
    protected $searchFields = 'id,aid,content';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\cms\Comment;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->relationSearch = true;
        $type = $this->request->param('type','');//评论类型'archives'=文档,'page'=单页,'bbs'=论坛,'news'=新闻,'video'=视频,'plaza'=广场;
        $type = explode('?',$type)[0];

        if (!$type){
            $type = json_decode($this->request->param('filter'),true)['type'] ?? '';
        }

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);

            $list = $this->model;

            if ($filter['type'] ?? null){
                $list = $list->where('type',$filter['type']);
            }

            if ($filter['comments'] ?? null){
                $filter['comments'] = explode(',',$filter['comments']);
                $list = $list->where('comments',$filter['comments']);
            }

            if ($filter['createtime'] ?? null){
                list($startTime, $endTime) = explode(' - ', $filter['createtime']);
                $list = $list->whereTime('createtime', 'between', [$startTime, $endTime]);
            }

            if ($filter['updatetime'] ?? null){
                list($startTime, $endTime) = explode(' - ', $filter['updatetime']);
                $list = $list->whereTime('updatetime', 'between', [$startTime, $endTime]);
            }


            if ($filter['status'] ?? null){
                $list = $list->where('status',$filter['status']);
            }

            //查询用户手机号
            if ($filter['user_mobile'] ?? null){
                $user_ids = User::where('mobile','like',"%{$filter['user_mobile']}%")->column('id');
                if ($user_ids){
                    $list = $list->whereIn('user_id',$user_ids);
                }
            }

            //查询用户昵称
            if ($filter['user_nickname'] ?? null){
                 $user_ids = User::where('nickname','like',"%{$filter['user_nickname']}%")->column('id');
                if ($user_ids){
                    $list = $list->whereIn('user_id',$user_ids);
                }
            }

            $sort = $this->request->param("sort", 'id');
            $order = $this->request->param("order", 'desc');

            $list = $list->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $index => $item) {
                $item->user->visible(['id', 'username', 'nickname', 'avatar']);
                $item->source = $item->source;
                $item->content = strip_tags($item->content); // 去掉HTML标签
                if (mb_strlen($item->content) > 0){
                    $item->content =mb_substr($item->content, 0, 20) . '...';//截取前20字
                }


            }

            $result = ['total' => $list->total(), 'rows' => $list->items()];
            return json($result);
        }
        $this->assignconfig("typeList", $this->model->getTypeList());
        return $this->view->fetch();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $aid_show = $this->getAContentShow($row['type'],$row['aid']);//获取关联文章详情

            $this->view->assign('aid_show', $aid_show);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    public function recyclebin()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $this->relationSearch = true;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->onlyTrashed()
                ->with(['archives', 'spage', 'user'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->onlyTrashed()
                ->with(['archives', 'spage', 'user'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $index => $item) {
                $item->user->visible(['id', 'username', 'nickname', 'avatar']);
                $type = $item['type'] == 'page' ? 'spage' : $item['type'];
                $item->url = $item->{$type} ? $item->{$type}->url : 'javascript:';
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function restore($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $config = get_addon_config('cms');
        $list = $this->model->onlyTrashed()->select();
        if ($list) {
            $ids = [];
            foreach ($list as $index => $item) {
                if ($item['status'] == 'normal') {
                    User::score($config['score']['postcomment'], $item['user_id'], '发表评论');
                }
                $ids[] = $item['id'];
            }
            $this->model->where('id', 'in', $ids);
            $this->model->restore('1=1');
            foreach ($list as $index => $item) {
                \app\admin\model\cms\Comment::refreshSourceComments($item['id']);
            }
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

    //获取关联文章详情
    private function getAContentShow(string $type, int $aid): array
    {
        //$type = news:新闻,bbs:论坛,video:视频,plaza:广场,live:直播,album:专辑
        switch ($type) {
            case 'news':
                $model = \app\admin\model\cms\News::find($aid);
                $res = [
                    'type'=>$type,

                    'image'=>'',//封面
                    'video_path'=>'',

                    'title'=>'',//标题
                    'content'=>$model['post_content'],//内容
                    'file_img'=>$model['file_img'],
                    'file_video'=>$model['file_video'],
                    'file_data'=>$model['file_data'],
                ];
                break;
            case 'bbs':
                $model = \app\admin\model\cms\Platepost::find($aid);
                $res = [
                    'type'=>$type,

                    'image'=>'',//封面
                    'video_path'=>'',

                    'title'=>$model['postname'],//标题
                    'content'=>$model['postcontent'],//内容
                    'file_img'=>$model['file_img'],
                    'file_video'=>$model['file_video'],
                    'file_data'=>$model['file_data'],
                ];
                break;
            case 'plaza':
                $model = PlazaPostModel::find($aid);
                $res = [
                    'type'=>$type,

                    'image'=>'',//封面
                    'video_path'=>'',

                    'title'=>$model['postname'],//标题
                    'content'=>$model['postcontent'],//内容
                    'file_img'=>$model['file_img'],
                    'file_video'=>$model['file_video'],
                    'file_data'=>$model['file_data'],
                ];
                break;
            case 'video':
                $model = \app\admin\model\cms\Video::find($aid);
                $res = [
                    'type'=>$type,

                    'image'=>obsurl($model['image']),//封面
                    'video_path'=>obsurl($model['video_path']),

                    'title'=>'',//标题
                    'content'=>'',//内容
                    'file_img'=>'',
                    'file_video'=>'',
                    'file_data'=>'',
                ];
                break;
            case 'album':
                 $model = \app\admin\model\cms\AlbumModel::find($aid);
                $res = [
                    'type'=>$type,

                    'image'=>obsurl($model['cover_image']),//封面
                    'video_path'=>'',

                    'title'=>$model['name'],//标题
                    'content'=>$model['introduction'],//内容
                    'file_img'=>'',
                    'file_video'=>'',
                    'file_data'=>'',
                ];
                break;
            case 'live':
                 $model = \app\admin\model\cms\Live::find($aid);
                $res = [
                    'type'=>$type,

                    'image'=>obsurl($model['image']),//封面
                    'video_path'=>'',

                    'title'=>$model['title'],//标题
                    'content'=>$model['description'],//内容
                    'file_img'=>'',
                    'file_video'=>'',
                    'file_data'=>'',
                ];
                break;
            default:
                return [];
        }

        if ($res['file_img']){
            $res['file_img'] = explode(',',$res['file_img']);
            foreach ($res['file_img'] as &$v){
                $v = obsurl($v);
            }
        }
        if ($res['file_video']){
            $res['file_video'] = explode(',',$res['file_video']);
            foreach ($res['file_video'] as &$v){
                $v = obsurl($v);
            }
        }
        if ($res['file_data']){
            $res['file_data'] = explode(',',$res['file_data']);
            foreach ($res['file_data'] as &$v){
                $v = obsurl($v);
            }
        }
        return $res;
    }

}
